package servlet;

import DAO.*;
import util.Page;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class BaseBackServlet extends HttpServlet {
    public abstract String add(HttpServletRequest request, HttpServletResponse response,Page page);
    public abstract String delete(HttpServletRequest request, HttpServletResponse respone,Page page);
    public abstract String edit(HttpServletRequest request, HttpServletResponse response,Page page);
    public abstract String update(HttpServletRequest request, HttpServletResponse response,Page page);
    public abstract String list(HttpServletRequest request, HttpServletResponse response,Page page);


    protected CategoryDAO categoryDAO = new CategoryDAO();
    protected OrderDAO orderDAO = new OrderDAO();
    protected OrderItemDAO orderItemDAO = new OrderItemDAO();
    protected ProductDAO productDAO = new ProductDAO();
    protected ProductImageDAO productImageDAO = new ProductImageDAO();
    protected PropertyDAO propertyDAO = new PropertyDAO();
    protected PropertyValueDAO propertyValueDAO = new PropertyValueDAO();
    protected ReviewDAO reviewDAO = new ReviewDAO();
    protected UserDAO userDAO = new UserDAO();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int start = 0;
        int count = 5;
        try{
            if(req.getParameter("page.start")!=null)
                start = Integer.parseInt( req.getParameter("page.start"));
        }
        catch (NumberFormatException e)
        {

        }
        try {
            if(req.getParameter("page.count")!=null)
                count = Integer.parseInt(req.getParameter("page.count"));
        }
        catch (NumberFormatException e)
        {

        }
        Page  page = new Page(start,count);
        String mymethod = (String) req.getAttribute("method");

        try {
            Method method = this.getClass().getMethod(mymethod,javax.servlet.http.HttpServletRequest.class,javax.servlet.http.HttpServletResponse.class,Page.class);
            String redirect = method.invoke(this,req,resp,page).toString();
            if(redirect.startsWith("@"))
                resp.sendRedirect(redirect.substring(1));
            else if(redirect.startsWith("%"))
                resp.getWriter().print(redirect.substring(1));
            else
                req.getRequestDispatcher(redirect).forward(req, resp);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
